package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

var (
	userSpecialBoxContentTableName string = "userSpBoxContent"
)

type SpecailBoxGood struct {
	Id    int64 `bson:"id"`    // 卡牌序号
	Tid   int64 `bson:"tid"`   // 卡牌道具Tid
	IsNew int64 `bson:"isNew"` // 新道具标识 0-新 1-旧
}

type SpecialBoxContent struct {
	Tid   int64            `bson:"tid"`   // Tid
	Goods []SpecailBoxGood `bson:"goods"` // 可选道具ID列表--Key:卡牌序号 Value-道具ID
}

type UserSpecialBoxContent struct {
	BaseM
	Uid          bson.ObjectId                `bson:"_id" json:"_id"`                   // m.User.Uid
	SpBoxContent map[int64]*SpecialBoxContent `bson:"spBoxContent" json:"spBoxContent"` // key-Tid
}

func NewUserSpecialBoxContent() cache.EntryI {
	return &UserSpecialBoxContent{
		SpBoxContent: make(map[int64]*SpecialBoxContent, 0),
	}
}

// 保存信息
func (uSpBoxContent *UserSpecialBoxContent) Save() (err error) {
	mdata := make(map[string]interface{}, 0)

	mdata["_id"] = uSpBoxContent.Uid

	if uSpBoxContent.SpBoxContent != nil && len(uSpBoxContent.SpBoxContent) > 0 {
		mdata["spBoxContent"] = uSpBoxContent.SpBoxContent
	}

	err = dbmodule.MgoDB.GameDB.Upsert(userSpecialBoxContentTableName, bson.M{"_id": uSpBoxContent.Uid}, mdata)
	if err != nil {
		return
	}
	return
}

func (uSpBoxContent *UserSpecialBoxContent) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uSpBoxContent.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uSpBoxContent.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "CardGameMulCombat_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uSpBoxContent.LoadData()
}

// 加载数据
func (uSpBoxContent *UserSpecialBoxContent) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne(userSpecialBoxContentTableName, bson.M{"_id": uSpBoxContent.Uid}, nil, &uSpBoxContent)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if uSpBoxContent.SpBoxContent == nil {
		uSpBoxContent.SpBoxContent = make(map[int64]*SpecialBoxContent, 0)
	}

	return
}

// 更新数据
func (uSpBoxContent *UserSpecialBoxContent) Update(val *UserSpecialBoxContent) {
	Cache.Put(userSpecialBoxContentTableName, uSpBoxContent.Uid.Hex(), val)
	val.UpdateData()
}

// 删除数据
func (uSpBoxContent *UserSpecialBoxContent) Delete() (err error) {
	Cache.Remove(userSpecialBoxContentTableName, uSpBoxContent.Uid.Hex())
	return dbmodule.MgoDB.GameDB.Remove(userSpecialBoxContentTableName, bson.M{"_id": uSpBoxContent.Uid})
}

// 获取数据
func (u *User) GetUserSpBoxContent() (r *UserSpecialBoxContent) {
	v, _ := Cache.Get(userSpecialBoxContentTableName, u.Uid.Hex())
	r = v.(*UserSpecialBoxContent)
	return
}

// 获取--特殊箱子数据中，最大的Tid索引，后续新增的，应该用这个数+1
func getMaxUserSpBoxMapTid(theMap map[int64]*SpecialBoxContent) (maxTid int64) {
	if theMap == nil || len(theMap) == 0 {
		maxTid = 0
	} else {
		// maxTid = int64(len(theMap)) // 不能直接设置长度，玩家有可能先完成了1，在完成2，此时长度为1，若再使用1+1=2会重复
		maxTid = 1
		for theKey, _ := range theMap {
			if theKey >= maxTid {
				maxTid = theKey
			}
		}
	}
	return
}

// 添加或创建--特殊箱子内容
func (u *User) AddOrCreateSpBoxContent() (userSPcontent *UserSpecialBoxContent, tid int64) {
	userSPcontent = u.GetUserSpBoxContent()
	if userSPcontent == nil {
		userSPcontent = &UserSpecialBoxContent{
			Uid:          u.Uid,
			SpBoxContent: make(map[int64]*SpecialBoxContent, 0),
		}
	}
	if userSPcontent.SpBoxContent == nil {
		userSPcontent.SpBoxContent = make(map[int64]*SpecialBoxContent, 0)
	}
	// 获取最大Tid， +1后，为新增数据的Tid
	maxTid := getMaxUserSpBoxMapTid(userSPcontent.SpBoxContent)
	maxTid = maxTid + 1
	// 添加新的content
	userSPcontent.SpBoxContent[maxTid] = &SpecialBoxContent{
		Tid:   maxTid,
		Goods: make([]SpecailBoxGood, 0),
	}
	defer userSPcontent.Update(userSPcontent)
	return userSPcontent, maxTid
}
